var study_current_page = 0;
var firstStudyLoad = false;

function buildStudyPager(number_of_hits){	
    if(number_of_hits > items_per_page){
            $("#study-pagination").show();
            $("#study-pagination").pagination(number_of_hits, {
                    items_per_page:items_per_page, 
                    callback:handleStudyPaginationClick,
                    next_text: 'Next',
                    prev_text: 'Prev',
                    link_to:"#",
                    num_edge_entries:2,
                    ellipse_text: '..'
            });
    }else{
            $("#study-pagination").hide();
    }
    firstStudyLoad = false;
}

function handleStudyPaginationClick(new_page_index, pagination_container) {	
    if(new_page_index != study_current_page){
        var s           = $('input[name=s]').val();

        var start 	= new_page_index*items_per_page;
        var end 	= (start + items_per_page);

        study_current_page = new_page_index;
        searchStudy(s,start,items_per_page);
    }
	
    return false;
}

function searchStudy(s, start,records){
        console.log('searching studies');
	if(s != ''){                
                var data = {
                    s:s, 
                    start:start, 
                    records:records
                };

		var lang = $("#select-language").val();
                if(lang != 'all')
                    data['lang'] = lang;
                
                if($("#series").val())
                    data['series'] = $("#series").val().join(',');


		if(current_lang.length != 0){
			data.lang = current_lang;
		}
		$.ajax({
                    url: backend+'/db/ddi/ws/study-search.xql',
                    dataType: 'json',
                    data: data,
                    success: studySearchDone
		});
                $('.study-tab').toggleClass('loading');
	}else{
		$("#qb-hits-count").html('');
		$("#qb-result").html('');
		$("#qb-pagination").hide();		
	}
}

function studySearchDone(data){
	if(parseInt(data.hits) > 0){
		$("#study-hits-count").html('('+data.hits+')');
		$("#study-pagination").show();
	
	
                console.log('results: '+data.hits);

                var output = '';
                if(data.studies['study'] instanceof Array){

                    $.each(data.studies['study'], function(i,study){
                        console.log('study loop ' + i);
                        output +=  renderStudy(study);
                    });
                }else{
                    output +=  renderStudy(data.studies['study']);
                }
                $("#study-result").html(output);

                //$(".question-block p").hide();
                //$(".question-block ."+$("#select-language").val()).show();
                //if this is the first result-set
                if(firstStudyLoad || data.hits < items_per_page){
                   buildStudyPager(data.hits);
                }

    	}else{
		$("#study-hits-count").html('');
		$("#study-result").html('');
		$("#study-pagination").hide();
	}
        $('.study-tab').toggleClass('loading');
}

function renderStudy(study){
    var output = '';
    output += '<div id="'+study.id+'" class="question-block">';
    output += '<h4><a href="'+backend+'/db/ddi/ws/export/study-xhtml.xql?id='+study.id+'">'+study.title.en+'</a></h4>';
    output += '<p>'+study['abstract']['en'].ellipsisText('end', 150)+'</p>';
    output += '<p><a class="marc" target="_blank" href="'+backend+'/db/ddi/ws/export/study-marc.xql?id='+study.id+'">marc</a> <a class="pdf" target="_blank" href="'+backend+'/db/ddi/ws/export/study-pdf.xql?id='+study.id+'">pdf</a> <a class="ddi" target="_blank" href="'+backend+'/db/ddi/ws/export/study-ddi.xql?id='+study.id+'">ddi</a></p>';
    /*
    if(count(study['other-material']['en']) > 0 && study['other-material']['en']['en'] instanceof Array){
         $.each(study['other-material']['en'], function(i,link){
             output += '<a href="'+link.url+'">'+link.label+'</a>&nbsp;&nbsp;&nbsp;';
        });       
    }
    */
    
    output += '</div>';
    return output;
}

String.prototype.ellipsisText = function(location, maxCharacters) {
    var text = this;
    if (this.length > 0 && this.length > maxCharacters) {
        if (typeof (location) == 'undefined') location = 'end';
        switch (location) {
            case 'center':
                var center = (maxCharacters / 2);
                text = this.slice(0, center) + '...' + this.slice(-center);
                break;
            case 'end':
                text = this.slice(0, maxCharacters - 3) + '...';
                break;
        }
    }
    return text;
}